﻿#if NETCOREAPP3_1||NETCOREAPP3_0
using RazorEngineCore;
#else
using RazorEngine;
using RazorEngine.Configuration;
using RazorEngine.Templating;

#endif

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JESAI.HtmlTemplate.Pdf.HtmlPaster
{
    public class HtmlByRazorTemplateExporter: IHtmlByRazorTemplateExporter
    {
        public HtmlByRazorTemplateExporter()
        {
            #if NETCOREAPP3_1 || NETCOREAPP3_0

#else
            var config = new TemplateServiceConfiguration();
            //config.ReferenceResolver = null;
          
            var razorEngineService = RazorEngineService.Create(config);
            Engine.Razor = razorEngineService;
#endif
        }
        public Task<string> ExportHtmlByRazorTemplateAsync<T>(T data, string htmlTemplate) where T : class
        {
            var result = RunCompileRazorTemplate(data, htmlTemplate);
            return Task.FromResult(result);
        }
        public string ExportHtmlByRazorTemplate<T>(T data, string htmlTemplate) where T : class
        {
            var result = RunCompileRazorTemplate(data, htmlTemplate);
            return result;
        }

        protected string RunCompileRazorTemplate<T>(T model,string razorTemplateStr) where T:class
        {
            if(string.IsNullOrWhiteSpace(razorTemplateStr))
                throw new ArgumentException("Razor模版不能为空");
#if NETCOREAPP3_1 || NETCOREAPP3_0
            RazorEngine razorEngine = new RazorEngine();
            IRazorEngineCompiledTemplate<RazorEngineTemplateBase<T>> template = razorEngine.Compile<RazorEngineTemplateBase<T>>(razorTemplateStr);

            string htmlString = template.Run(instance=> {
                instance.Model = model;
            });
            return htmlString;
#else
            var htmlString= Engine.Razor.RunCompile(razorTemplateStr, razorTemplateStr.GetHashCode().ToString(), typeof(T), model);
            return htmlString;
#endif
        }
    }
}
